/* eslint-disable camelcase */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { Avatar, Progress, Popover, Icon, Tooltip, Modal } from 'antd';
import runningImg from '../../images/running.png';
import stopImg from '../../images/stop.png';
import { UPDATING_STAGE_PROCESS_MAP } from '@util/constants';
import './index.less';
import updataSvg from './images/updata.svg';
const { confirm } = Modal;

class ClusterDeviceUpdateCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nodesProgress: [],
      isSystemProgress: false,
      isResourceProgress: false,
      systemProgress: 0,
      resourceProgress: 0,
      resourceUpgradMsg: '',
      progress: 0,
      systemUpdateNode: true,
      resourceUpdateNode: true,
      node: null
    };
    this.errorTimes = 0;
  }
  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { nodesProgress } = this.props;
    if (JSON.stringify(nodesProgress) !== JSON.stringify(nextProps.nodesProgress)) {
      this.setState({ nodesProgress: nextProps.nodesProgress }, this.getIsProgress);
    }
  }

  //方法基本一样等待重构优化
  setSystemProgress = (status, stage) => {
    const { getNodeList, isFirstRequest, setIsFirstRequest } = this.props;
    this.setState({ isSystemProgress: true });
    if (status === 'updating') {
      this.setState({ systemProgress: UPDATING_STAGE_PROCESS_MAP[stage] });
      this.setState({ resourceUpdateNode: false });
    } else if (status === 'success') {
      this.setState({ isSystemProgress: false });
      isFirstRequest ? setIsFirstRequest() : getNodeList();
    }
  };

  setResourceProgress = (status, stage) => {
    const { getNodeList, isFirstRequest, setIsFirstRequest } = this.props;
    this.setState({ isResourceProgress: true });
    if (status === 'updating') {
      this.setState({ resourceProgress: UPDATING_STAGE_PROCESS_MAP[stage] });
      this.setState({ systemUpdateNode: false });
    } else if (status === 'success') {
      this.setState({ isResourceProgress: false });
      isFirstRequest ? setIsFirstRequest() : getNodeList();
    }
  };

  getIsProgress = () => {
    const { nodesProgress } = this.state;
    const ip = _.get(this.props, 'device.node_ip');
    const node = _.find(nodesProgress, i => i.ip === ip);
    let item = nodesProgress.find(r => r.status === 'updating');
    this.setState({ node: item });
    if (!node) {
      // 如果有其他节点正在执行
      if (item) {
        if (item?.expire * 1000 > Date.now()) {
          this.setState({ systemUpdateNode: false, resourceUpdateNode: false });
        }
      }
      return;
    }
    this.setState({ systemUpdateNode: true, resourceUpdateNode: true });
    const { status, stage } = node;
    if (node.update_type === 'system') {
      this.setSystemProgress(status, stage);
    }
    if (node.update_type === 'resource') {
      this.setResourceProgress(status, stage);
    }
  };

  sureModel = (nodeIp, type, key) => {
    const { updateNode } = this.props;
    confirm({
      title: '注意,升级过程中该扫描节点正在执行的任务将受到影响',
      className: 'system-update-confirm-modal',
      okText: '确定',
      cancelText: '取消',
      width: '500px',
      onOk() {
        updateNode(nodeIp, type, key);
      },
      onCancel() {}
    });
  };

  render() {
    const { device, key, edition, resourceEdition } = this.props;
    const nodeIp = _.get(device, 'node_ip');
    const noderole = _.get(device, 'node_role');
    const deviceStats = _.get(device, 'device_stats.version', '');
    const repositoryStats = _.get(device, 'repository_stats.version', '');
    const master = noderole === 'master';
    // 没有id说明ksp没获取到设备信息
    const status = _.get(device, 'status') === 'online';
    const {
      isSystemProgress,
      systemProgress,
      isResourceProgress,
      resourceProgress,
      systemUpdateNode,
      resourceUpdateNode,
      systemVisible,
      resourceVisible,
      node
    } = this.state;
    const compareVersions = (version1, version2) => {
      // 将版本号拆分为主要版本和次要版本
      const v1Arr = version1.split('.').map(Number);
      const v2Arr = version2.split('.').map(Number);

      for (let i = 0; i < v1Arr.length; i++) {
        if (v1Arr[i] > v2Arr[i]) {
          return 1;
        } else if (v1Arr[i] < v2Arr[i]) {
          return -1;
        }
      }

      // 如果主要和次要版本号都相等，则返回 0
      return 0;
    };
    const handleMouseOver = type => {
      type === 'system'
        ? this.setState({ systemVisible: true })
        : this.setState({ resourceVisible: true });
    };

    const handleMouseOut = type => {
      type === 'system'
        ? this.setState({ systemVisible: false })
        : this.setState({ resourceVisible: false });
    };
    const systemLater = edition !== deviceStats;
    const resourceLater = compareVersions(repositoryStats, resourceEdition) === -1;
    return (
      <div
        className={`cluster-device-update-card ${_.get(device, 'node_role', '-')} ${
          status ? 'active' : 'unactive'
        }`}
      >
        <div className="cluster-device-update-card-content">
          <div style={{ color: '#1E1F23' }}>{nodeIp}</div>
          <div>{master ? '管理节点' : '扫描节点'}</div>
          <div className={'df aic'}>
            系统版本:
            {!isSystemProgress && (
              <>
                <span style={{ color: systemLater ? 'red' : '' }}>{deviceStats || '--'}</span>
                {systemLater && (
                  <>
                    <Popover content="该扫描节点与管理节点系统版本号不一致，请先将该扫描节点系统版本升级至管理节点系统版本">
                      <Icon
                        style={{ color: 'red', marginLeft: 5, height: 15 }}
                        type="info-circle"
                      />
                    </Popover>
                    <Tooltip
                      visible={systemUpdateNode && systemVisible && node && !resourceUpdateNode}
                      title={`${node?.role === 'slave' ? '扫描节点' : '管理节点'}${
                        node?.ip
                      }正在进行${
                        node?.update_type === 'sysmg' ? '系统' : '资源库'
                      }升级，建议不要同时升级，请稍后重试`}
                      style={{ background: 'red' }}
                    >
                      {!master && (
                        <img
                          src={updataSvg}
                          width={16}
                          style={{
                            margin: '-1px 0 0 3px',
                            filter: !systemUpdateNode ? 'grayscale(100%)' : null
                          }}
                          className="pointer"
                          onClick={() => {
                            if (!systemUpdateNode || !status) {
                              return;
                            }
                            this.sureModel(nodeIp, 'system', key);
                          }}
                          onMouseOver={() => handleMouseOver('system')}
                          onMouseOut={() => handleMouseOut('system')}
                        />
                      )}
                    </Tooltip>
                  </>
                )}
              </>
            )}
            {isSystemProgress && (
              <Progress
                size="small"
                percent={systemProgress}
                strokeWidth={100}
                style={{ width: 128, marginLeft: 15 }}
              />
            )}
          </div>
          <div className="cluster-device-update-card-content-media-box">
            资源库版本:
            {!isResourceProgress && (
              <>
                <Tooltip title={repositoryStats}>
                  <span style={{ color: resourceLater ? 'red' : '' }}>
                    {repositoryStats || '--'}
                  </span>
                </Tooltip>
                <Tooltip
                  visible={!resourceUpdateNode && resourceVisible && node && !systemUpdateNode}
                  title={`${node?.role === 'slave' ? '扫描节点' : '管理节点'}${node?.ip}正在进行${
                    node?.update_type === 'sysmg' ? '系统' : '资源库'
                  }升级，建议不要同时升级，请稍后重试`}
                  disabled={true}
                  style={{ background: 'red' }}
                >
                  {resourceLater && !master && (
                    <>
                      <Popover content="该扫描节点与管理节点资源库版本号不一致，请先将该扫描节点资源库版本升级至管理节点资源库版本">
                        <Icon
                          style={{ color: 'red', marginLeft: 5, height: 15, width: 16 }}
                          type="info-circle"
                        />
                      </Popover>
                      <img
                        src={updataSvg}
                        width={16}
                        style={{
                          margin: '-3px 0 0 3px',
                          filter: !systemUpdateNode ? 'grayscale(100%)' : null
                        }}
                        className="pointer"
                        onClick={() => {
                          if (!resourceUpdateNode || !status) {
                            return;
                          }
                          this.sureModel(nodeIp, 'resource', key);
                        }}
                        onMouseOver={() => handleMouseOver('resource')}
                        onMouseOut={() => handleMouseOut('resource')}
                      />
                    </>
                  )}
                </Tooltip>
              </>
            )}
            {isResourceProgress && (
              <Progress
                size="small"
                percent={resourceProgress}
                strokeWidth={100}
                style={{ width: 128, marginLeft: 15 }}
              />
            )}
          </div>
        </div>
        <div className={`fan ${status && 'running'}`}>
          <Popover content={status ? '运行中' : '无法连接'}>
            <Avatar src={status ? runningImg : stopImg} style={{ width: 24, height: 24 }} />
          </Popover>
        </div>
      </div>
    );
  }
}

ClusterDeviceUpdateCard.propTypes = {
  device: PropTypes.object,
  nodesProgress: PropTypes.array,
  updateNode: PropTypes.func,
  edition: PropTypes.string,
  key: PropTypes.number,
  resourceEdition: PropTypes.object,
  getNodeList: PropTypes.func,
  isFirstRequest: PropTypes.bool,
  setIsFirstRequest: PropTypes.func
};

export default ClusterDeviceUpdateCard;
